package com.butterfly.mvc.util;

import com.butterfly.mvc.servlet.MvcBean;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by DouDou on 2016/9/19.
 */
public class MvcParser {

    public MvcParser(){

    }

    public static Map parseXml(String xmlPath) throws DocumentException {
        SAXReader reader = new SAXReader();
        Document document = reader.read(new File(xmlPath));
        Element root = document.getRootElement();
        Element fbs = root.element("formBeans");
        List<Element> formBeans = fbs.elements();
        Map<String,String> mapFormBean = new HashMap<String, String>();
        for(Iterator<Element> it = formBeans.iterator();it.hasNext();){
            Element e = it.next();
            mapFormBean.put(e.attributeValue("name"),e.attributeValue("type").toString());
            System.out.println(e.attributeValue("name") +"="+e.attributeValue("type").toString());
        }
        Element as = root.element("actions");
        List<Element> actions = as.elements();
        Map<String,MvcBean> mapMvcBean = new HashMap<String,MvcBean>();
        for(Iterator<Element> it=actions.iterator();it.hasNext();){
            Element e = it.next();
            MvcBean bean = new MvcBean();
            bean.setName(e.attributeValue("name"));
            bean.setPath(e.attributeValue("path"));
            bean.setActionType(e.attributeValue("type"));
            bean.setMethod(e.attributeValue("method"));
            bean.setFormType(mapFormBean.get(bean.getName()));
            List<Element> fs = e.elements();
            for(Iterator<Element> i=fs.iterator();i.hasNext();){
                Element item = i.next();
                bean.getForwards().put(item.attributeValue("name"),item.attributeValue("url"));
            }
            mapMvcBean.put(bean.getPath(),bean);
            System.out.println(bean);
        }
        return mapMvcBean;
    }

    public static void main(String args[]){
        try {
            MvcParser.parseXml("E:\\IT\\WorkSpace\\idea\\mvc\\src\\main\\resources\\mvc\\mvc-config.xml");
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
